package top.chatgqt.SmartChargeStation.mqtt.client.factory;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import top.chatgqt.SmartChargeStation.mqtt.client.conf.MqttProps;
import top.chatgqt.SmartChargeStation.mqtt.client.model.MqttConstants;

/**
 * 主题订阅
 */
@EnableIntegration
@Configuration
@Slf4j
public class InBounderSubscribe {

    @Resource
    private MqttProps props;

    @Resource
    private FactoryBuilder factory;

    @Resource
    private InBoundMessageRev messageRev;

    /**
     * 接收通道
     */
    @Bean(name = MqttConstants.IN_CHANNEL)
    public MessageChannel inChannel() {
        return new DirectChannel();
    }

    // 订阅主题的适配器
    @Bean
    public MessageProducer getAdaptor() {
        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(
                props.getClientId(), factory.getClientFactory(), props.getTopic());

        // 设置转换器
        adapter.setConverter(new DefaultPahoMessageConverter());
        // 设置订阅通道
        adapter.setOutputChannel(inChannel());
        return adapter;
    }

    // 创建消息处理器
    @Bean
    @ServiceActivator(inputChannel = MqttConstants.IN_CHANNEL)
    public MessageHandler inHandler() {
        return this.messageRev;
    }
}
